const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');

// 假设您有一个包含 10 万个文件名的数组
const directoryPath = 'D:\\work\\bishun_data';

function generateFilesToCommit() {
  const files = fs.readdirSync(path.join(directoryPath, 'poem_detail'), { withFileTypes: true });
  return files.map(file => 'poem_detail' + '/' + file.name);
}


// 函数用于提交一批文件
function commitBatch(files) {
  return new Promise((resolve, reject) => {
    const gitCommands = files.map(file => `git add ${file}`).join(' && ');
    exec(`${gitCommands} && git commit -m "Commit batch of files"`, (error, stdout, stderr) => {
      if (error) {
        console.error(`Error committing batch: ${error}`);
        reject(error);
      } else {
        console.log(`Committed batch of ${files.length} files`);
        resolve();
      }
    });
  });
}

// 函数用于推送已提交的更改
function pushChanges() {
  return new Promise((resolve, reject) => {
    exec('git push', (error, stdout, stderr) => {
      if (error) {
        console.error(`Error pushing changes: ${error}`);
        reject(error);
      } else {
        console.log('Changes pushed to remote repository');
        resolve();
      }
    });
  });
}

// 分批提交并推送所有文件
async function commitAndPushAllFilesInBatches(files) {
  const batchSize = 100;
  for (let i = 0; i < files.length; i += batchSize) {
    const batch = files.slice(i, i + batchSize);
    try {
      await commitBatch(batch);
      await pushChanges();
    } catch (error) {
      console.error('An error occurred while committing and pushing files:', error);
      // Handle the error as needed, e.g., by breaking the loop or retrying
      break;
    }
  }
  console.log('All files have been committed and pushed.');
}

// 开始分批提交并推送
const filesToCommit = generateFilesToCommit();
console.log(filesToCommit[0])
commitAndPushAllFilesInBatches(filesToCommit).catch(console.error);
